package com.cloudptt.wp;


import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.func.call.IIncommingCall;
import com.cloudptt.api.product.func.call.single.LaunchCallInfo;
import com.cloudptt.api.product.func.sys.fsm.SysConst;
import com.cloudptt.api.product.func.sys.listener.SysListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.wp.ui.Login;
import com.cloudptt.wp.ui.MainActivity;
import com.cloudptt.wp.ui.call.group.GroupCallVideoActivity;
import com.cloudptt.wp.ui.call.single.CallActivity;
//import com.gyf.barlibrary.ImmersionBar;
import com.cloudptt.wp.ui.call.single.fv.FloatWindowService;
import com.cloudptt.wp.ui.dlg.CallInfoDlg;
import com.cloudptt.wp.ui.message.SessionActivity;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.http.operator.IHttpAddrOpCb;
import com.cloudptt.api.product.func.sys.listener.SysMsgListener;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 继承Application
 *
 * @author admin
 *
 */
public class SysApplication extends Application implements SysMsgListener, IIncommingCall
{
	public static final String APPID = "appid=1442820561";//0x55ffb1d1
	//	public static String THIS_FILE = "SysApplication";
	public static String APP_KEY = "ptt/wuping";
	public static final String GROUP_CREATE_RESULT_ACTION = "org.hytera.create_group_ACTION";
	private Product product = null;
	private IHttpAddrOpCb addrUptListener = null;
	private AppCloseReceiver appCloseReceiver;
	private TelephonyManager tm = null;
	private AppPhoneStateListener phoneStateListener = null;
	private Activity currentActivity;
	private boolean isActivityVisible = true;
	private Map<String, CallInfoDlg> dlgMap = null;
	public static boolean IsLockScreen = false;
	@Override
	public void onCreate()
	{
		super.onCreate();
		Log.debug(this.getClass(),"onCreate");
		CrashHandler crashHandler = CrashHandler.getInstance();
		crashHandler.init(this);
//		ImmersionBar.with(SysApplication.this)
//				.statusBarColorTransform(R.color.gradient_start) // 起始色
//				.statusBarColorTransformEnd(R.color.gradient_end) // 结束色
//				.barColorTransformEnable(true) // 启用渐变色
//				.init();
//		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//		phoneStateListener = new AppPhoneStateListener();
//		tm.listen(phoneStateListener,PhoneStateListener.LISTEN_CELL_LOCATION | PhoneStateListener.LISTEN_CELL_INFO);
		appCloseReceiver = new AppCloseReceiver(this);
		IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		registerReceiver(appCloseReceiver, filter);
		this.dlgMap = new HashMap<>();
		registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
			@Override
			public void onActivityCreated(Activity activity, Bundle bundle) {
				Log.debug(SysApplication.class, "onActivityCreated -- activity:" + activity);
			}

			@Override
			public void onActivityStarted(Activity activity) {
				Log.debug(SysApplication.class, "onActivityStarted -- activity:" + activity);
			}

			@Override
			public void onActivityResumed(Activity activity) {
				Log.debug(SysApplication.class, "onActivityResumed -- activity:" + activity);
				currentActivity = activity; // 更新当前Activity引用
				isActivityVisible = true;
			}

			@Override
			public void onActivityPaused(Activity activity) {
				Log.debug(SysApplication.class, "onActivityPaused -- activity:" + activity);
				isActivityVisible = false;
			}

			@Override
			public void onActivityStopped(Activity activity) {
				Log.debug(SysApplication.class, "onActivityStopped -- activity:" + activity);
			}

			@Override
			public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
				Log.debug(SysApplication.class, "onActivitySaveInstanceState -- activity:" + activity);
			}

			@Override
			public void onActivityDestroyed(Activity activity) {
				Log.debug(SysApplication.class, "onActivityDestroyed -- activity:" + activity);
			}
			// 其他生命周期方法省略...
		});
//		AndroidRemoteDebugger.init(this);
	}

	public void checkIncommingDlg()
	{
		Log.debug(this.getClass(),"checkIncommingDlg dlgMap = " + dlgMap);
		Set<String> keySet = dlgMap.keySet();
		for(Iterator<String> itor = keySet.iterator();itor.hasNext();)
		{
			try
			{
				String callKey = itor.next();
				Log.debug(this.getClass(),"checkIncommingDlg callKey = " + callKey);
				CallInfoDlg dlg = dlgMap.remove(callKey);
				Log.debug(this.getClass(),"checkIncommingDlg dlg = " + dlg);
				if(dlg != null)
				{
					AddrInfo peerAddrInfo = dlg.getPeerAddrInfo();
					LaunchCallInfo info = dlg.getInfo();
					CallInfoDlg newDlg = new CallInfoDlg(currentActivity, peerAddrInfo, info, false);
					dlgMap.put(callKey, newDlg);
					newDlg.show();
				}
			}catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}


	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
		Log.debug(this.getClass(),"onLowMemory");
	}
	public void onTrimMemory(int level)
	{
		super.onTrimMemory(level);
		Log.debug(this.getClass(),"onTrimMemory level = " + level);
	};


	@Override
	public void onTerminate()
	{
		super.onTerminate();
		Log.debug(this.getClass(),  "onTerminate");
		product.doExit();

		SharedPreferences sharedPreferences = getSharedPreferences(MainActivity.KEY_HOME, Context.MODE_PRIVATE);
		sharedPreferences.edit().putBoolean(MainActivity.KEY_NAME_ISFIRST, false).commit();

		ScreenManager.getScreenManager().popAllActivity();
		SystemClock.sleep(2000);
		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(0);

		if(tm != null
				&& phoneStateListener != null)
		{
			tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
		}
		unregisterReceiver(appCloseReceiver);

	}



	public void checkServiceIsAlive()
	{
		Log.debug(this.getClass(),  "checkServiceIsAlive");
		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
			String className = service.service.getClassName();
			Log.debug(this.getClass(),  "checkServiceIsAlive className = " + className);
			if ("com.cloudptt.api.product.pjsua2.service.PjsuaService".equals(className)) {
				// Service存活
				break;
			}
		}
	}

	public void creatProduct(SysListener listener)
	{
		Log.debug(this.getClass(),  "creatProduct product = " + product);
		checkServiceIsAlive();
		if(product == null){
			this.product = new Product(this,ProductConst.ProductType_NAPP_RADIO,ProductConst.Product_Simple);
		}
		this.product.setLogStatus();
		this.product.setPCallClass(CallActivity.class, FloatWindowService.class);
		this.product.setGCallVideoClass(GroupCallVideoActivity.class);
		this.product.setMsgSessionClass(SessionActivity.class);
		this.product.setSysMsgListener(this);
		this.product.setIncommingCall(this);
		this.product.setSysListener(this.getClass().getName(),listener);
//		this.product.checkCurVersion(currentActivity,false,false,null);

//		Intent createintent = new Intent(GROUP_CREATE_RESULT_ACTION);
//		sendBroadcast(createintent);
	}

	public Product getProduct() {
		return product;
	}

	@Override
	public void receiveSysMsg(String type)
	{
		Log.debug(this.getClass(), "receiveSysMsg type = " + type);
		if(type != null)
		{
			if(type.equals(SysConst.SysMsg_NAT_KEEPALIVE_ERR)
					|| type.equals(SysConst.SysMsg_KICKOFF))
			{
				int errStrId = getErrStrId(type);
				if(errStrId != 0) {
					CommDlg.showToast(this, errStrId);
				}
				if(product == null){
					this.product = this.getProduct();
				}
				this.product.doLogout();
				goToLogin();
			}
		}
	}
	private int getErrStrId(String type)
	{
		if(type.equals(SysConst.SysMsg_NAT_KEEPALIVE_ERR)) {
			return R.string.nat_keepalive_err;
		}
		else if (type.equals(SysConst.SysMsg_KICKOFF))
		{
			return R.string.kickoff_err;
		}
		return 0;
	}
	private void goToLogin()
	{
		Log.debug(this.getClass(), "goToLogin begin");
		ScreenManager.getScreenManager().popAllActivityExceptOne(this,MainActivity.class);
		Intent intent = new Intent();
		intent.setClass(currentActivity, Login.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
		//		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		Log.debug(this.getClass(), "goToLogin end");
	}

	public void setAddrUptListener(IHttpAddrOpCb addrUptListener) {
		this.addrUptListener = addrUptListener;
	}

	@Override
	public void incommingCall(AddrInfo peerAddrInfo, LaunchCallInfo info) {
		Log.debug(this.getClass(), "IncommingCall currentActivity = " + currentActivity + " isActivityVisible = " + isActivityVisible + " peerAddrInfo = " + peerAddrInfo + " info = " + info);

		String callKey = info.getCallKey();
		CallInfoDlg dlg = new CallInfoDlg(currentActivity, peerAddrInfo, info, false);
		dlgMap.put(callKey, dlg);

		if(currentActivity != null
				&& isActivityVisible) {
			dlg.show();
		}
		Log.debug(this.getClass(), "IncommingCall callKey = " + callKey + " dlgMap = " + dlgMap);
	}
	@Override
	public void dlgClose(String callKey)
	{
		Log.debug(this.getClass(), "dlgClose callKey = " + callKey );
		CallInfoDlg dlg = dlgMap.remove(callKey);
		try
		{
			if(dlg != null)
			{
				dlg.dismiss();
				dlg = null;
			}
		}catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
